using UnityEngine;
using UnityEngine.SceneManagement;

[AddComponentMenu("MyGame/GameManager")]
public class GameManager : MonoBehaviour
{
    public static GameManager instance;
    public int m_score = 0;
    public static int m_hi_score = 100;

    protected Player m_player;

    public AudioClip m_musicClip;
    protected AudioSource m_audio;

    void Awake()
    {
        instance = this;
    }

    void Start()
    {
        m_audio = GetComponent<AudioSource>();

        GameObject obj = GameObject.FindGameObjectWithTag("Player");
        if (obj != null)
        {
            m_player = obj.GetComponent<Player>();
        }
    }

    void Update()
    {
        if (!m_audio.isPlaying)
        {
            m_audio.clip = m_musicClip;
            m_audio.Play();
        }

        if (Time.timeScale > 0 && Input.GetKeyDown(KeyCode.Escape))
        {
            Time.timeScale = 0;
        }
    }

    void OnGUI()
    {
        if (Time.timeScale == 0)
        {
            if (GUI.Button(new Rect(Screen.width / 2 - 50, Screen.height * 0.4f, 100, 30), "Continue"))
            {
                Time.timeScale = 1;
            }
            if (GUI.Button(new Rect(Screen.width / 2 - 50, Screen.height * 0.6f, 100, 30), "Exit"))
            {
                Application.Quit();
            }
        }

        float life = 0;
        if (m_player != null)
        {
            life = m_player.m_life;
        }
        else
        {
            GUI.skin.label.fontSize = 50;
            GUI.skin.label.alignment = TextAnchor.LowerCenter;
            GUI.Label(new Rect(0, Screen.height * 0.2f, Screen.width, 60), "GAME OVER");

            GUI.skin.label.fontSize = 20;
            if (GUI.Button(new Rect(Screen.width / 2 - 50, Screen.height * 0.5f, 100, 30), "Retry"))
            {
                SceneManager.LoadScene(SceneManager.GetActiveScene().name);
            }
        }

        GUI.skin.label.fontSize = 15;
        GUI.Label(new Rect(5, 5, 100, 30), "Ammor " + life);

        GUI.skin.label.alignment = TextAnchor.LowerCenter;
        GUI.Label(new Rect(0, 5, Screen.width, 30), "Record:" + m_hi_score);
        GUI.Label(new Rect(0, 25, Screen.width, 30), "Score:" + m_score);
    }

    protected int m_temp_sum_point = 0;

    public void AddScore(int point)
    {
        m_score += point;
        m_temp_sum_point += point;
        if (m_score > m_hi_score)
        {
            m_hi_score = m_score;
        }
        if (m_temp_sum_point > 200)
        {
            m_temp_sum_point = 0;
            m_player.m_life++;
        }
    }
}